# 超级管理员

from web.models import SuperAdmin, Users
from django.http import JsonResponse
from django import forms
from web import utils
from django.forms.models import model_to_dict
from django.core.paginator import Paginator
from web.apis.module import Module
tools = utils.Utils()
module = Module()
class AdminForm(forms.ModelForm):
    class Meta:
        model = SuperAdmin
        fields = ['user_id']


# 添加超级管理员
def add_super_admin(request):
    user_id = request.POST.get('user_id')
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='用户不存在'))
    
    form = AdminForm(request.POST)
    if form.is_valid():
        # 判断是否已经存在超级管理员
        if SuperAdmin.objects.filter(user_id=user_id).exists():
            return JsonResponse(tools.Response(code=400, message='用户已经是超级管理员'))
        form.save()
        
        return JsonResponse(tools.Response(code=200, message='添加成功'))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))


# 删除超级管理员
def delete_super_admin(request):
    user_id = request.GET.get('user_id')
    super_admin = SuperAdmin.objects.filter(user_id=user_id).first()
    if super_admin:
        super_admin.delete()
        return JsonResponse(tools.Response(code=200, message='删除成功'))
    else:
        return JsonResponse(tools.Response(code=400, message='超级管理员不存在'))



# 获取超级管理员
def get_super_admin(request):
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    super_admin = SuperAdmin.objects.all()
    paginator = Paginator(super_admin, page_size)
    page_data = paginator.page(page)
    data = []
    for i in page_data.object_list:
        data.append(module.user_data_format(i.user_id))
    total = paginator.count
    result = {
        'data': data,
        'total': total,
        'page': page,
        'page_size': page_size
    }
    return JsonResponse(tools.Response(code=200, message='获取成功', data=result))

# 判断是否是超级管理员
def is_super_admin(request):
    user_id = request.GET.get('user_id')
    if SuperAdmin.objects.filter(user_id=user_id).exists():
        return JsonResponse(tools.Response(code=200, message='', data=True))
    else:
        return JsonResponse(tools.Response(code=400, message='', data=False))
    

